package StructuralPattern.Proxy.Dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Client {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        InvocationHandler handler = null;
        AbstractUserDAO userDAO = new UserDAO();
        handler = new DAOLogHandler(userDAO);
        AbstractUserDAO proxy = null;

        // 动态创建代理对象，用于代理一个AbstractUserDAO类型的真实主题对象
        proxy = (AbstractUserDAO) Proxy.newProxyInstance(AbstractUserDAO.class.getClassLoader(),new Class[]{AbstractUserDAO.class},handler);
        proxy.findUserById("Michael");  //调用代理对象的业务方法

        System.out.println("--------------------------------------");

        AbstractDocumentDAO documentDAO = new DocumentDAO();
        handler = new DAOLogHandler(documentDAO);
        AbstractDocumentDAO proxy_new = null;

        // 动态创建代理对象，用于代理一个AbstractDocumentDAO类型的真实主题对象
        proxy_new = (AbstractDocumentDAO) Proxy.newProxyInstance(AbstractDocumentDAO.class.getClassLoader(),new Class[]{AbstractDocumentDAO.class},handler);
        proxy_new.deleteDocumentById("009");

        System.out.println("-------------------------------------");

        // 使用getProxyClass需要两步获得Proxy，使用newProxyInstance省去麻烦
        Class proxyClass = Proxy.getProxyClass(
                AbstractDocumentDAO.class.getClassLoader(), new Class[] { AbstractDocumentDAO.class });
        AbstractDocumentDAO proxy_new_new = (AbstractDocumentDAO) proxyClass.
                getConstructor(new Class[] { InvocationHandler.class }).
                newInstance(new Object[] { handler });
        proxy_new_new.deleteDocumentById("001");
    }
}
